const router = require('koa-router')()
const Person=require('../../dbs/models/person')


router.prefix('/users')

router.get('/', function (ctx, next) {
  ctx.body = 'this is a users response!'
})

router.get('/bar', function (ctx, next) {
  ctx.body = 'this is a users/bar response'
})


router.post('/addPerson', async function (ctx, next) {
  global.console.log(ctx.request.body)
  const person =new Person({
    name:ctx.request.body.name,
    age:ctx.request.body.age
  })
  let code;
  try {
     await   person.save()
     code=0; 
  } catch (error) {
     code=-1
  }
  ctx.body={
    code:code
  }
})


router.post('/getPerson',async function (ctx, next) {
  let code;
  let result;
  try {
     result=await Person.findOne({name:ctx.request.body.name})
     code=0; 
  } catch (error) {
     code=-1
  }
  ctx.body={
    code:code,
    result:result
  }

})




router.post('/updatePerson',async function (ctx, next) {
  let code;
  let result;
  try {
     result=await Person.where({name:ctx.request.body.name}).update({
       age:ctx.request.body.age
     })
     code=0; 
  } catch (error) {
     code=-1
  }
  ctx.body={
    code:code,
    result:result
  }

})


router.post('/deletePerson',async function (ctx, next) {
  let code;
  let result;
  try {
     result=await Person.where({name:ctx.request.body.name}).remove()
     code=0; 
  } catch (error) {
     code=-1
  }
  ctx.body={
    code:code,
    result:result
  }

})




module.exports = router
